package org.microframework.base.core.util;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;

/**
 * IP地址工具类
 */
public class IpUtil {

    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST_IPV4 = "127.0.0.1";
    private static final String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1";
    private static final String SEPARATOR = ",";

    /**
     * 获取请求IP
     * 
     * @param request HttpServletRequest
     * @return IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return UNKNOWN;
        }
        
        String ip = request.getHeader("x-forwarded-for");
        if (isEmptyIP(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isEmptyIP(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (isEmptyIP(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isEmptyIP(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (isEmptyIP(ip)) {
            ip = request.getRemoteAddr();
            if (LOCALHOST_IPV4.equals(ip) || LOCALHOST_IPV6.equals(ip)) {
                // 根据网卡取本机配置的IP
                try {
                    ip = java.net.InetAddress.getLocalHost().getHostAddress();
                } catch (java.net.UnknownHostException e) {
                    // ignore
                }
            }
        }
        
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15 && ip.indexOf(SEPARATOR) > 0) {
            ip = ip.substring(0, ip.indexOf(SEPARATOR));
        }
        
        return isEmptyIP(ip) ? UNKNOWN : ip;
    }

    /**
     * 获取请求IP（适用于WebFlux）
     * 
     * @param request ServerHttpRequest
     * @return IP地址
     */
    @SuppressWarnings("null")
	public static String getIpAddr(ServerHttpRequest request) {
        if (request == null) {
            return UNKNOWN;
        }
        
        HttpHeaders headers = request.getHeaders();
        String ip = headers.getFirst("x-forwarded-for");
        if (isEmptyIP(ip)) {
            ip = headers.getFirst("Proxy-Client-IP");
        }
        if (isEmptyIP(ip)) {
            ip = headers.getFirst("X-Forwarded-For");
        }
        if (isEmptyIP(ip)) {
            ip = headers.getFirst("WL-Proxy-Client-IP");
        }
        if (isEmptyIP(ip)) {
            ip = headers.getFirst("X-Real-IP");
        }
        if (isEmptyIP(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
            if (LOCALHOST_IPV4.equals(ip) || LOCALHOST_IPV6.equals(ip)) {
                // 根据网卡取本机配置的IP
                try {
                    ip = java.net.InetAddress.getLocalHost().getHostAddress();
                } catch (java.net.UnknownHostException e) {
                    // ignore
                }
            }
        }
        
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15 && ip.indexOf(SEPARATOR) > 0) {
            ip = ip.substring(0, ip.indexOf(SEPARATOR));
        }
        
        return isEmptyIP(ip) ? UNKNOWN : ip;
    }

    /**
     * 判断IP地址是否为空
     */
    private static boolean isEmptyIP(String ip) {
        return !StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip);
    }
    
    /**
     * 是否为本地IP
     */
    public static boolean isLocalhost(String ip) {
        return LOCALHOST_IPV4.equals(ip) || LOCALHOST_IPV6.equals(ip);
    }
    
    /**
     * 判断是否为未知IP
     */
    public static boolean isUnknown(String ip) {
        return !StringUtils.hasText(ip) || "unknown".equalsIgnoreCase(ip);
    }
    
    /**
     * 判断是否为内网IP
     */
    public static boolean internalIp(String ip) {
        if (isUnknown(ip)) {
            return false;
        }
        
        // 本地回环地址
        if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
            return true;
        }
        
        // 内网IP地址范围
        String[] ipParts = ip.split("\\.");
        if (ipParts.length != 4) {
            return false;
        }
        
        int first = Integer.parseInt(ipParts[0]);
        int second = Integer.parseInt(ipParts[1]);
        
        // 10.0.0.0/8
        if (first == 10) {
            return true;
        }
        
        // 172.16.0.0/12
        if (first == 172 && second >= 16 && second <= 31) {
            return true;
        }
        
        // 192.168.0.0/16
        if (first == 192 && second == 168) {
            return true;
        }
        
        return false;
    }
    
    /**
     * 获取IP地址的地理位置
     * 
     * @param ip IP地址
     * @return 地理位置
     */
    public static String getIpLocation(String ip) {
        if (isEmptyIP(ip)) {
            return UNKNOWN;
        }
        
        // 判断是否为本地或内网IP
        if (isLocalhost(ip)) {
            return "本地";
        }
        
        if (internalIp(ip)) {
            return "内网";
        }
        
        // 此处可以接入第三方IP地址库进行查询，如: 高德、百度、淘宝等
        // 简化起见，目前仅返回IP地址
        return "未知位置";
    }
    
    /**
     * IPv4地址转换为字节数组
     */
    @SuppressWarnings("unused")
	private static byte[] textToNumericFormatV4(String text) {
        if (text.length() == 0) {
            return null;
        }

        byte[] bytes = new byte[4];
        String[] elements = text.split("\\.", -1);
        try {
            if (elements.length != 4) {
                return null;
            }
            for (int i = 0; i < elements.length; i++) {
                int value = Integer.parseInt(elements[i]);
                if (value < 0 || value > 255) {
                    return null;
                }
                bytes[i] = (byte) (value & 0xff);
            }
        } catch (NumberFormatException e) {
            return null;
        }
        
        return bytes;
    }
} 